package com.frame.controller;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSONObject;
import com.csvreader.CsvReader;
import com.frame.common.tool.DBTool;
import com.frame.common.tool.DbMetaTool;
import com.frame.common.tool.ZcurdTool;
import com.frame.common.util.StringUtil;
import com.frame.ext.render.csv.CsvRender;
import com.frame.model.ZcurdField;
import com.frame.model.ZcurdHead;
import com.frame.service.ZcurdService;
import com.frame.vo.ZcurdMeta;
import com.jfinal.aop.Duang;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;

/**
 * 在线表单
 * @author 钟世云 2016.2.5
 */
public class ZcurdController extends BaseController {
	
	public void listPage() {
		int headId = getHeadId();
		ZcurdService zcurdService = Duang.duang(ZcurdService.class);
		ZcurdMeta metaData = zcurdService.getMetaData(headId);
		
		flushDictData(metaData);
		//System.out.println("刷新字典数据成功！");
		setAttr("headId", headId);
		setAttrs(metaData.toMap());
		setAttr("queryPara",  JSONObject.toJSONString(ZcurdTool.getQueryPara(getParaMap())));
		render("listPage.html");
	}
	
	public void listData() {
		int headId = getHeadId();
		ZcurdService zcurdService = Duang.duang(ZcurdService.class);
		ZcurdMeta metaData = DbMetaTool.getMetaData(headId);
		ZcurdHead head = metaData.getHead();
		
		Object[] queryParams = getQueryParams();
		String[] properties = (String[]) queryParams[0];
		String[] symbols = (String[]) queryParams[1];
		Object[] values = (Object[]) queryParams[2];
		
		String orderBy = getOrderBy();
		if(StringUtil.isEmpty(orderBy)) {
			orderBy = head.getIdField() + " desc";
		}
		
		renderDatagrid(
				ZcurdTool.replaceDict(metaData, DBTool.findByMultProperties(head.getTableName(), properties, symbols, values, orderBy, getPager())), 
				DBTool.countByMultProperties(head.getTableName(), properties, symbols, values), 
				zcurdService.getFooter(metaData, properties, symbols, values));
	}
	
	//增加页面
	public void addPage() {
		int headId = getHeadId();
		ZcurdService zcurdService = Duang.duang(ZcurdService.class);
		ZcurdMeta metaData = zcurdService.getMetaData(headId);
		flushDictData(metaData);
		
		setAttr("headId", headId);
		setAttrs(metaData.toMap());
		setAttr("queryPara", ZcurdTool.getQueryPara(getParaMap()));
	}
	
	//增加
	public void add() {
		int headId = getHeadId();
		ZcurdMeta metaData = DbMetaTool.getMetaData(headId);
		ZcurdHead head = metaData.getHead();
		
		ZcurdService zcurdService = Duang.duang(ZcurdService.class);
		Map<String, String[]> paraMap = getParaMap();
		zcurdService.add(getHeadId(), paraMap);
		
		addOpLog("[" + head.getFormName() + "] 增加");
		renderSuccess();
	}
	
	//修改页面
	public void updatePage() {
		int headId = getHeadId();
		ZcurdService zcurdService = Duang.duang(ZcurdService.class);
		ZcurdMeta metaData = zcurdService.getMetaData(headId);
		flushDictData(metaData);
		
		setAttr("headId", headId);
		setAttrs(metaData.toMap());
		setAttr("model", zcurdService.get(headId, getParaToInt("id")).getColumns());
		render("updatePage.html");
	}
	
	//修改
	public void update() {
		int headId = getHeadId();
		ZcurdMeta metaData = DbMetaTool.getMetaData(headId);
		ZcurdHead head = metaData.getHead();
		
		Map<String, String[]> paraMap = getParaMap();
		ZcurdService zcurdService = Duang.duang(ZcurdService.class);
		System.out.println(getParaToInt("id"));
		zcurdService.update(headId, getParaToInt("id"), paraMap);
		
		addOpLog("[" + head.getFormName() + "] 修改");
		renderSuccess();
	}
	
	//删除
	public void delete() {
		int headId = getHeadId();
		ZcurdMeta metaData = DbMetaTool.getMetaData(headId);
		ZcurdHead head = metaData.getHead();
		
		Integer[] ids = getParaValuesToInt("id[]");
		ZcurdService zcurdService = Duang.duang(ZcurdService.class);
		zcurdService.delete(getHeadId(), ids);
		
		addOpLog("[" + head.getFormName() + "] 删除");
		renderSuccess();
	}
	
	//详情页面
	public void detailPage() {
		int headId = getHeadId();
		ZcurdMeta metaData = DbMetaTool.getMetaData(headId);
		ZcurdService zcurdService = Duang.duang(ZcurdService.class);
		
		Record row = zcurdService.get(headId, getParaToInt("id"));
		setAttr("headId", headId);
		setAttrs(metaData.toMap());
		setAttr("model", ZcurdTool.replaceDict(metaData, row));
		render("detailPage.html");
	}
	
	//导出csv
	public void exportCsv() {
		int headId = getHeadId();
		ZcurdMeta metaData = DbMetaTool.getMetaData(headId);
		ZcurdHead head = metaData.getHead();
		List<ZcurdField> fieldList = metaData.getFieldList();
		flushDictData(metaData);
		
		Object[] queryParams = getQueryParams();
		String[] properties = (String[]) queryParams[0];
		String[] symbols = (String[]) queryParams[1];
		Object[] values = (Object[]) queryParams[2];
		
		String orderBy = getOrderBy();
		if(StringUtil.isEmpty(orderBy)) {
			orderBy = head.getIdField() + " desc";
		}
		
		List<Record> list = ZcurdTool.replaceDict(headId, 
				DBTool.findByMultProperties(head.getTableName(), properties, symbols, values));
		List<String> headers = new ArrayList<String>();
		List<String> clomuns = new ArrayList<String>();
		for (ZcurdField zcurdField : fieldList) {
			if(zcurdField.getInt("is_show_list") == 1) {
				headers.add(zcurdField.getStr("column_name"));
				clomuns.add(zcurdField.getStr("field_name"));
			}
		}
		CsvRender csvRender = new CsvRender(headers, list);
		csvRender.clomuns(clomuns);
		csvRender.fileName(head.getStr("form_name"));
		
		addOpLog("[" + head.getFormName() + "] 导出cvs");
		render(csvRender);
	}
	//导入Csv文件页面
	public void importCsvPage() {
			int headId = getHeadId();			
			setAttr("headId", headId);			
			render("importCsv.html");
		}
	//导  入csv
	public void importCsv() {
//			UploadFile file=getFile("file_path");
//			File source = file.getFile();
//			FileInputStream fis = null;
//			try {
//				 fis = new FileInputStream(source);
//			} catch (FileNotFoundException e1) {
//				
//				e1.printStackTrace();
//			}
			int headId = getHeadId();
			String file_Path=getPara("file_path");	
			
			ZcurdMeta metaData = DbMetaTool.getMetaData(headId);
			ZcurdHead head = metaData.getHead();
			List<ZcurdField> fieldList = metaData.getFieldList();
			
			String clomuns = "";
			String values="";
			for (ZcurdField zcurdField : fieldList) {
				if(!zcurdField.getStr("field_name").equals("id")){
					if(zcurdField.getInt("is_show_list")==1){
					clomuns+=zcurdField.getStr("field_name")+",";
					 values+="?"+",";
					}
				}
			}
			CsvReader reader = null;
			try {
				reader = new CsvReader(file_Path, ',', Charset.forName("GBK"));
//				reader = new CsvReader(fis,Charset.forName("GBK"));
				//路过表头
		    	reader.readHeaders();
			} catch (FileNotFoundException e) {
				
				e.printStackTrace();
			} catch (IOException e) {
				
				e.printStackTrace();
			}
			Object[] list ={};
			try {
				while (reader.readRecord()) {
					//把头保存起来
//					if (reader.getCurrentRecord()==0){
//					header = reader.getValues();
//					}
					//获取当前记录位置
//					System.out.print(reader.getCurrentRecord() + header[0]+".\n");
					//读取一条记录+				
//					csvList.add(reader.getValues());
//					System.out.println(csvList);	
					list=reader.getValues();
					Db.update("insert into "+head.getTableName()+"("+clomuns.substring(0, clomuns.length()-1)+") values("+values.substring(0, values.length()-1)+")",list);
					
				}
			} catch (Exception e) {
				renderFailed(e.getMessage());
				return;
			}			
			reader.close();
			addOpLog("[" + head.getFormName() + "] 导入cvs");
			renderSuccess();
				    	
		}
	/**
	 * 获得表单id
	 */
	private int getHeadId() {
		String headId = getAttr("headId");
		return Integer.parseInt(headId);
	}

	/**
	 * 刷新字典数据
	 */
	private void flushDictData(ZcurdMeta metaData) {
		for (ZcurdField zcurdField : metaData.getFieldList()) {
			String dictSql = zcurdField.getStr("dict_sql");
			if(StringUtil.isNotEmpty(dictSql)) {
				Map<String, Object> dictData = DbMetaTool.getDictData(dictSql);
				metaData.getDictMap().put(zcurdField.getStr("field_name"), dictData);
				zcurdField.put("dict", dictData);
			}
		}
	}

}
